package com.caption.api.manager;

import com.caption.api.entity.IDCarAuthCondition;
import com.caption.api.handle.base.AbstractHandler;
import com.caption.api.handle.impl.IDCardAuthHandler;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutionException;

/**
 *
 */
@Component
public class ApiManager {

    private ThreadLocal<AbstractHandler> threadLocal = new ThreadLocal<>();

    public <T> void setHandler(T condition,String version){
        setHandler(condition);
        setVersion(version);
    }

    private void setVersion(String version){
        threadLocal.get().setVersion(version);
    }

    private <T> void setHandler(T condition){
         AbstractHandler handler = null;
         if(condition instanceof IDCarAuthCondition){
             handler = new IDCardAuthHandler((IDCarAuthCondition)condition);
         }
         threadLocal.set(handler);
    }

    public <T> T call(){
        T t = null;
        try {
            t = threadLocal.get().call();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        clear();
        return t;
    }

    private void clear(){
        threadLocal.remove();
    }

}
